<template>
  <el-dialog :title="titleMap[type]" :visible.sync="_visible" width="650px" destroy-on-close @close="handleCloseDialog">
    <!--    <div>{{ JSON.stringify(mode) }}</div>-->
    <el-form
      ref="dataForm"
      :rules="rules"
      :model="mode"
      label-position="left"
      label-width="100px"
      style="width: 500px; margin-left:50px;"
    >
      <el-form-item label="任务名称" prop="name">
        <el-input v-model="mode.name" :disabled="type==='update'" placeholder="请输入任务名称" @input="mode.name = mode.name !== undefined ? mode.name.trim(): ''" />
      </el-form-item>
      <el-form-item label="任务状态" prop="timeRange">
        <el-radio-group v-model="mode.status">
          <el-radio
            v-for="item in [
              {label: '1', text: '激活'},
              {label: '0', text: '挂起'}
            ]"
            :key="item.label"
            :label="item.label"
          >{{ item.text }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="任务类型" prop="type">
        <el-radio-group v-model="mode.type" :disabled="type === 'update' && /[12]/ig.test(mode.type)">
          <el-radio
            v-for="item in [ {label: '1', text: '测试任务'}, {label: '2', text: '前线任务'} ]"
            :key="item.label"
            :label="item.label"
          >{{ item.text }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-divider content-position="left">产品约束</el-divider>
      <el-form-item label="产品名称" prop="product">
        <el-select
          v-model="mode.product"
          filterable
          style="width:100%"
          placeholder="请选择产品"
        >
          <el-option
            v-for="item in products"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-divider content-position="left">当前版本</el-divider>
      <el-form-item label="版本" prop="srcV">
        <el-select
          v-model="mode.srcV"
          multiple
          allow-create
          filterable
          default-first-option
          style="width:100%"
          placeholder="请选择当前版本"
          @focus="queryVersions"
        >
          <el-option
            v-for="item in versionList"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="其他条件" prop="otherSrcCond">
        <el-input v-model="mode.otherSrcCond" placeholder="请输入当前版本标识, 类型：json" />
      </el-form-item>
      <el-divider content-position="left">目标版本</el-divider>
      <el-form-item label="版本" prop="dstV">
        <el-select
          v-model="mode.dstV"
          style="width:100%"
          filterable
          placeholder="请选择目标版本"
          @focus="queryVersions"
        >
          <el-option
            v-for="item in versionList"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="其他条件" prop="otherDstCond">
        <el-input v-model="mode.otherDstCond" placeholder="请输入目标版本标识, 类型：json" />
      </el-form-item>
      <el-divider />
      <el-form-item label="升级方式" prop="updateType">
        <el-radio-group v-model="mode.updateType">
          <el-radio
            v-for="item in [
              {label: '1', text: '手动'},
              {label: '2', text: '自动'},
              {label: '0', text: '无限制'}
            ]"
            :key="item.label"
            :label="item.label"
          >{{ item.text }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="IMEI" prop="imei">
        <el-radio-group v-model="mode.imeiType" @change="imeiRadioChange">
          <el-radio
            v-for="item in [
              {label: 'equal', text: '等于'},
              {label: 'multi_v', text: '多值'},
              {label: 'range', text: '范围'},
              {label: 'close', text: '无限制'}
            ]"
            :key="item.label"
            :label="item.label"
          >{{ item.text }}</el-radio>
        </el-radio-group>
        <el-input
          v-if="mode.imeiType !== 'close'"
          v-model="mode.imei"
          :type="mode.imeiType!=='multi_v'? 'text': 'textarea'"
          :autosize="{ minRows: 1, maxRows: 4}"
          :disabled="mode.imeiType === 'close'"
          :placeholder="imeiHolder[mode.imeiType]"
        />
      </el-form-item>
      <el-form-item label="生效时间" prop="timeRange">
        <div style="float: left; margin-right: 8px">
          <el-checkbox v-model="mode.timeEnable" @change="timeEnableCheckBoxChange" />
        </div>
        <div style="width: 378px; float: left">
          <el-time-picker
            v-model="mode.timeRange[0]"
            :disabled="!mode.timeEnable"
            value-format="timestamp"
            placeholder="开始时间点"
          />
          <span style="margin-left: 8px; margin-right: 8px">至</span>
          <el-time-picker
            v-model="mode.timeRange[1]"
            :disabled="!mode.timeEnable"
            value-format="timestamp"
            placeholder="结束时间点"
          />
        </div>
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input
          v-model="mode.description"
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 4}"
          placeholder="请输入内容"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCloseDialog">
        取消
      </el-button>
      <el-button type="primary" @click="type==='update'?updateVersion():createVersion()">
        提交
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import fota from '../../api/fota'

export default {
  name: 'CreateDialog',
  props: {
    'mode': {
      type: Object,
      default: function() {
        return { type: '1', imeiType: 'equal', status: '1', updateType: '1', timeEnable: false, timeRange: [] }
      }
    },
    'type': {
      type: String,
      default: function() {
        return 'create'
      }
    },
    'visible': Boolean
  },
  data() {
    return {
      products: [],
      versionList: [],
      defaultFormData: { type: '1', imeiType: 'equal', status: '1', updateType: '1', timeEnable: false, timeRange: [] },
      imeiHolder: {},
      titleMap: {
        update: '修改升级计划',
        create: '新增升级计划',
        copy: '复制升级计划'
      },
      rules: []
    }
  },
  computed: {
    _mode: {
      get: function() {
        return this.mode
      },
      set: function(val) {
        this.$emit('update:mode', val)
      }
    },
    _visible: {
      get: function() {
        return this.visible
      },
      set: function(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  created() {
    this.initRules()
    this._mode = JSON.parse(JSON.stringify(this.defaultFormData))
    this.imeiHolder = {
      close: '',
      equal: '请输入IMEI值，不允许空值',
      multi_v: '请输入IMEI值，多个值用","分割',
      range: '格式: [a,b]，"[]"包含边界值，"()"不包含'
    }
  },
  mounted() {
    this.getProductList()
  },
  methods: {
    reloadTable: function() {
      this.handleCloseDialog()
      this.$emit('callback')
    },
    dealSrcV: function(param) {
      let tmp = ''
      for (let i = 0; i < param.srcV.length; i++) {
        tmp += param.srcV[i].trim()
        if (i !== param.srcV.length - 1) {
          tmp += ','
        }
      }
      return tmp
    },
    dealCond: function(cond) {
      if (cond.imei) {
        cond.imei = cond.imei.replace(/\n/g, '')
      }
      return JSON.stringify(cond)
    },
    createVersion() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const param = this.constructApiData()
          param.srcV = this.dealSrcV(param)
          param.cond = this.dealCond(param.cond)
          fota.insertPlan(param).then(() => {
            fota.notifySuccess(`创建升级计划成功！`)
            this.reloadTable()
          }, () => {
            this.reloadTable()
            fota.notifyError(`创建升级计划失败！`)
          })
        }
      })
    },
    updateVersion() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const param = this.constructApiData()
          param.srcV = this.dealSrcV(param)
          param.cond = this.dealCond(param.cond)
          fota.updatePlan(param).then(() => {
            fota.notifySuccess('修改升级计划成功！')
            this.reloadTable()
          }, () => {
            this.reloadTable()
            fota.notifyError(`修改升级计划失败！`)
          })
        }
      })
    },
    constructApiData() {
      const params = JSON.parse(JSON.stringify(this._mode))
      params.cond = { type: params.type, imei: params.imei, updateType: params.updateType, timeRange: params.timeRange }
      return params
    },
    handleCloseDialog() {
      this._visible = false
      this.$refs['dataForm'].clearValidate()
      this._mode = JSON.parse(JSON.stringify(this.defaultFormData))
    },
    getProductList() {
      const self = this
      fota.queryAllProduct().then(res => {
        self.products = res.data
      }, () => {
        fota.notifyError(`查询产品信息失败！`)
      })
    },
    queryVersions() {
      if (this._mode.product !== undefined && this._mode.product !== '') {
        const self = this
        fota.queryVersionsByproduct(this._mode.product).then(res => {
          self.versionList = res.data
        }, () => {
          fota.notifyError(`查询版本信息失败！`)
        })
      }
    },
    initRules() {
      const imeiCheck = (rule, value, callback) => {
        let ok
        let errMsf = '请输入指定格式的IMEI值'
        switch (this.mode.imeiType) {
          case 'close':
            ok = true
            break
          case 'equal':
            ok = value !== undefined && /[\w\d]+/g.test(value)
            break
          case 'range':
            ok = value !== undefined && /^[\[(][\w\d]*[,，][\w\d]*[)\]]$/g.test(value)
            break
          case 'multi_v': {
            if (value !== undefined) {
              const rule1Match = /[\w\d]+([,，][\w\d]+)*/g.test(value)
              const rule2Match = !(this._mode.type === '0' && value.split(/[,，]/ig).length > 10)
              ok = rule1Match && rule2Match
            }
            if (!ok) {
              errMsf = '多值IMEI在计划类型为测试时，最多允许设置10个'
            }
            break
          }
          default:
            ok = false
        }
        if (ok) {
          callback()
        } else {
          callback(new Error(errMsf))
        }
      }

      const planExistByName = (rule, value, callback) => {
        if (this._mode.name && this.type !== 'update') {
          fota.existPlanByName(value).then(resp => {
            if (resp.data === true) {
              callback(new Error('升级计划已存在，请重命名'))
            } else {
              callback()
            }
          }, () => {
            const msg = '服务器异常，请稍后再试或联系管理员'
            fota.notifyError(msg)
            callback(new Error(msg))
          })
        } else {
          callback()
        }
      }
      this.rules = {
        name: [
          { required: true, message: '请输入升级计划名称', trigger: 'blur' },
          { min: 2, max: 30, message: '请输入2位到30位长度的字符', trigger: 'blur' },
          { validator: planExistByName, trigger: 'blur' }
        ],
        product: [
          { required: true, message: '请选择产品', trigger: 'blur' }
        ],
        srcV: [
          { required: true, message: '请选择当前版本', trigger: 'blur' }
        ],
        dstV: [
          { required: true, message: '请选择目标版本', trigger: 'blur' }
        ],
        imei: [
          { validator: imeiCheck, trigger: 'blur' }
        ]
      }
    },
    imeiRadioChange() {
      this.$refs['dataForm'].clearValidate(['imei'])
      if (this._mode.imei !== undefined) {
        this._mode.imei = ''
      }
    },
    timeEnableCheckBoxChange(val) {
      this.$refs['dataForm'].clearValidate(['timeRange'])
      if (!val) {
        this._mode.timeRange = []
      } else {
        this._mode.timeRange = [new Date().getTime(), new Date().getTime()]
      }
    }
  }
}
</script>

<style scoped>
    /* 日期选择框的宽度 */
    .el-date-editor.el-input, .el-date-editor.el-input__inner {
        width: 45.8%;
    }

    /deep/ .el-dialog__body {
        height: 500px;
        overflow-y: auto;
    }
    /* 设置分割线文字位置及颜色 */
    .el-divider__text.is-left {
      left: 0;
      padding-left: 0;
      color: #C0C4CC;
    }
</style>
